package weibo;

import user.UserSession;
import utils.JsonOut;
import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

@WebServlet(name = "WeiboCommentServlet")
public class WeiboCommentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        String blogId = request.getParameter("blog_id");
        if (blogId == null || blogId.isEmpty()){
            out.println(JsonOut.error(201, "no_blog_id"));
            return;
        }

        String fromNum = request.getParameter("m");
        String toNum = request.getParameter("n");

        if (fromNum == null || fromNum.isEmpty()) {
            fromNum = "0";
        }

        if (toNum == null || toNum.isEmpty()){
            toNum = "10";
        }

        int fromInt = 0;
        int toInt = 10;

        try{
            fromInt = Integer.parseInt(fromNum);
            toInt = Integer.parseInt(toNum);
            if (toInt < fromInt) toInt = fromInt;
        }catch (Exception e){
            e.printStackTrace();
        }

//        ResultSet commentSet = (new MysqlUtils()).listWeiboComment(blogId, fromInt, toInt);
        HttpSession session = request.getSession();
        ArrayList<HashMap<String, String>> array = Weibo.getComment(blogId, fromInt, toInt, session);
        if (array != null) out.println(JsonOut.common(0, "comment_list", array));
        else out.println(JsonOut.error(500, "sql_sth_wrong"));

    }
}
